#-*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__all__ = ['make_exporter']

from Qt4 import QtGui
from Qt4.compat import getsavefilename

from pyLot.dataconverter import (DataConverterHandler, ErrReprDoNotExists,
                                 IDataRepr)
from pyLot.core import isimplementation, check_implements

import logging
LOGGER = logging.getLogger('pyLot.plugins')

class GuiExportButton(QtGui.QToolButton):
  def __init__(self, datarepr, converter=None, fmts=None, max_length=None):
    QtGui.QToolButton.__init__(self)
#    menu = QtGui.QMenu(u'export')
    self.action_to_fmt_id = {}

    if converter :
      self.converter = converter
    else :
      self.converter = DataConverterHandler()

    self.datarepr = datarepr

    if fmts is None :
      fmts = self.converter.fmts

    fmt_ids = self.converter.getConverterOutputFormats(self.datarepr.identifier,
      fmts=fmts, max_length=max_length)

    for fmt_id in fmt_ids :
      fmt = fmts[fmt_id]
      action = QtGui.QAction(u'Export %s' % fmt.alias, self)
      action.triggered.connect(self.onActionTriggered)
      self.action_to_fmt_id[action] = fmt_id
      self.addAction(action)

    if fmt_ids :
      self.setDefaultAction(action)

    else :
      self.setEnabled(False)
      self.setText(u'No exporter available')
      tt = u'Please install dataconverter plugins and restart application'
      LOGGER.info(u'IDataWriter for IDataRepr %r not found' % self.datarepr.identifier)
      self.setToolTip(tt)

  def getDatarepr(self):
    return self.__datarepr

  def setDatarepr(self, datarepr):
    if isinstance(datarepr, (str, unicode)):
      try :
        self.__datarepr = self.converter.reprs[str(datarepr)]
      except KeyError :
        raise ErrReprDoNotExists(str(datarepr))
    elif isimplementation(datarepr, IDataRepr) :
      self.__datarepr = datarepr
    else :
      check_implements(u'datarepr', datarepr, [IDataRepr], quick=True)

  def delDatarepr(self):
    del self.__datarepr


  def onActionTriggered(self):
    fmt_id = self.action_to_fmt_id[self.sender()]
    fmt = self.converter.fmts[fmt_id]
    output_path, filters = getsavefilename(self, u'Export %s' % fmt.name, filters=fmt.alias)
    if output_path :
      self.converter.convertData(self.datarepr.identifier, fmt_id, self.datarepr,
                                 input_mode='data', output_mode='path',
                                 output_path=output_path)

  datarepr = property(getDatarepr, setDatarepr, delDatarepr, "Current datarepr, used by export")


def make_exporter(datarepr, handler=None, fmts=None, max_length=None):
  u"""
  :param datarepr: IDataRepr implementation or IDataRepr identifier
  :type datarepr: IDataRepr, str
  """
  button = GuiExportButton(datarepr, handler, fmts=fmts, max_length=max_length)
  return button

